﻿using SanlieHash;
using SanlieHash.OtherHash;
using System;
using System.Security.Cryptography;
namespace suamod.core
{
    public class SuaRadom : IDisposable
    {
        internal const int Zlength = 26;
        internal const char Z = 'Z';
        internal const char z = 'z';
        internal const int _9length = 10;
        internal const char _9 = '9';
        private RandomNumberGenerator gen { get; set; }
        internal ADLER32 adler32 { get; set; }
        public SuaRadom()
        {
            adler32 = new ADLER32();
            adler32.New();
            gen = RandomNumberGenerator.Create();
        }
        public SuaRadom(string seed) : this()
        {
            if (! string.IsNullOrEmpty(seed))
            adler32.Update(FastHash.GetMD5Bytes(seed));
        }
        public int Int(int max, int min=0)
        {
            var u =new byte[4];
            gen.GetBytes(u);
            adler32.Update(u);
            return new Random((int)adler32.MakeUInt32()).Next(min, max);
        }
        public static string MakeNumber(int length, string code= "")
        {
            using (var radom = new SuaRadom(code))
                return radom.Number(length);
        }
        public static string MakeNumberAndText(int length, string code = "")
        {
            using (var radom = new SuaRadom(code))
                return radom.NumberAndText(length);
        }

        public string Number(int length)
        {
            var password = new char[length];

            for (int i = 0; i < length; i++)
                password[i] = (char)(_9 - Int(_9length));
            return new string(password);
        }
        public string Text(int length)
        {
            var password = new char[length];

            for (int i = 0; i < length; i++)
                if (Int(2) != 0) password[i] = (char)(z - Int(Zlength));
                else password[i] = (char)(Z - Int(Zlength));
            return new string(password);
        }
        public string NumberAndText(int length)
        {
            var password = new char[length];

            for (int i = 0; i < length; i++)
                if (Int(2) == 0)
                {
                    password[i] = (char)(_9 - Int(_9length));
                }
                else
                {
                    if (Int(2) != 0) password[i] = (char)(z - Int(Zlength));
                    else password[i] = (char)(Z - Int(Zlength));
                }
            return new string(password);
        }

        public void Dispose()
        {
#if NETSTANDARD2_0
            gen.Dispose();
#endif
        }
    }
}
